﻿using MapleLeaf.Application.CookBook;
using MapleLeaf.Application.CookBook.Models;
using MapleLeaf.Core;
using MapleLeaf.Core.Dto;
using MapleLeaf.Model.CookBook.Organization.Entity;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace MapleLeaf.WebApi.CookBook.Controllers.SystemManagement {
    /// <summary>
    /// 部门管理
    /// </summary>
    public class DepartmentController : ApiBaseController {

        private readonly SystemClient _systemClient;
        private readonly OrganizationClient _organizationClient;
        /// <summary>
        /// 构造函数
        /// </summary>
        public DepartmentController(OrganizationClient organizationClient, SystemClient systemClient) {
            _organizationClient = organizationClient;
            _systemClient = systemClient;
        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<DepartmentVo>>> GetDepartmentList() {
            var whereExp = Expressionable.Create<DepartmentEntity>();
            var list = await _organizationClient.GetDepartmentListAsync(whereExp.ToExpression());
            var voList = list.GetTree();
            return Success(voList);
        }
        /// <summary>
        /// 获取部门选项  
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<OptionType>>> GetDepartmentOptions() {
            var whereExp = Expressionable.Create<DepartmentEntity>();
            whereExp = whereExp.And(it => it.Status == 1);
            var list = await _organizationClient.GetDepartmentListAsync(whereExp.ToExpression());
            var voList = list.GetOptionTree();
            return Success(voList);
        }
        /// <summary>
        /// 保存部门
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveDepartment(DepartmentVo data) {
            var entity = data.Adapt<DepartmentEntity>();
            _ = await _organizationClient.SaveDepartmentAsync(entity);
            return Success();
        }
        /// <summary>
        /// 获取部门
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<DepartmentVo>> GetDepartment(long id) {
            var entity = await _organizationClient.GetDepartmentAsync(id);
            var vo = entity.Adapt<DepartmentVo>();
            return Success(vo);
        }
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> DeleteDepartment(long id) {
            var res = await _organizationClient.DeleteDepartmentAsync([id]);
            return res ? Success() : Fail();
        }
    }
}
